package rts

import (
	"encoding/base64"

	v1 "code.byted.org/bytertc/whiteboard_server/biz/api/pb/v1"
	"code.byted.org/bytertc/whiteboard_server/biz/pkg/biz_error"
	"github.com/pkg/errors"
	"google.golang.org/protobuf/proto"
)

func decodeRTM(message string) (*v1.OnWireRequest, error) {
	data, err := DecodeBase64(message)
	if err != nil {
		return nil, err
	}
	req := &v1.OnWireRequest{}
	err = proto.Unmarshal(data, req)
	return req, biz_error.DecodeError.Wrap(errors.Wrap(err, "fail to unmarshal protobuf"))
}

func DecodeBase64(message string) ([]byte, error) {
	data, err := base64.StdEncoding.DecodeString(message)
	return data, biz_error.DecodeError.Wrap(errors.Wrap(err, "fail to decode base64"))
}

func EncodeBase64(data []byte) string {
	return base64.StdEncoding.EncodeToString(data)
}

type sendRoomUnicastParam struct {
	AppID   string `json:"AppId"`
	RoomID  string `json:"RoomId"`
	From    string `json:"From"`
	To      string `json:"To"`
	Binary  bool   `json:"Binary"`
	Message string `json:"Message"`
}

type sendBroadcastParam struct {
	AppID   string `json:"AppId"`
	RoomID  string `json:"RoomId"`
	From    string `json:"From"`
	Binary  bool   `json:"Binary"`
	Message string `json:"Message"`
}

// CommonResponse 统一的JSON返回结果
type CommonResponse struct {
	ResponseMetadata ResponseMetadata
	Result           interface{} `json:"Result,omitempty"`
}

type ResponseMetadata struct {
	RequestId string
	Service   string    `json:",omitempty"`
	Region    string    `json:",omitempty"`
	Action    string    `json:",omitempty"`
	Version   string    `json:",omitempty"`
	Error     *ErrorObj `json:",omitempty"`
}

type ErrorObj struct {
	CodeN   int
	Code    string
	Message string
}

type RoomExitRequest struct {
	AppID  string `json:"app_id"`
	RoomID string `json:"room_id"`
	Reason string `json:"reason"`
}

type RoomExitResponse struct {
}

type SEngine struct {
	AppID     string            `json:"app_id"`
	ServerUID string            `json:"server_uid"`
	Rooms     map[string]*SRoom `json:"rooms"`
}

type SRoom struct {
	AppID          string `json:"app_id"`
	RoomID         string `json:"room_id"`
	LastActiveTime int64  `json:"last_active_time"`
}

type HeartBeatRequest struct {
	IP      string              `json:"ip"`
	Port    string              `json:"port"`
	Engines map[string]*SEngine `json:"engines"`
	Cpu     float64             `json:"cpu"`
	Mem     float64             `json:"mem"`
}

type HeartBeatResponse struct {
}

type InstanceExitRequest struct {
	IP   string `json:"ip"`
	Port string `json:"port"`
}

type InstanceExitResponse struct {
}
